package me.yuzho.study.concurrency;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static net.mindview.util.Print.*;

class BlockedMutex {
    private Lock lock = new ReentrantLock();
    
    public BlockedMutex() {
        // Acquire it right away, to demonstrate interruption
        // of a task blocked on a ReentrantLock
        lock.lock();
    }
    
    public void f() {
        try {
            // This will never be available to a second task
            lock.lockInterruptibly(); //Special call,使用该方法来获取锁，该锁会被中断
            print("lock acquried in f()");
        } catch (InterruptedException e) {
            //e.printStackTrace();
            print("Interrupted from lock acquisition in f()");
        }
    }
}

class Blocked2 implements Runnable {
    BlockedMutex blocked = new BlockedMutex();

    @Override
    public void run() {
        print("Waiting for f() in BlockedMutex");
        blocked.f();
        print("Broken out of blocked call");
    } 
}
/** ReetrantLock上阻塞的任务具备可以被中断的能力，这与synchronized方法或临界区上阻塞的任务完全不同
 * @author yzhou-citrix
 *
 */
public class Interrupting2 {

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Blocked2());
        t.start();
        
        TimeUnit.SECONDS.sleep(1);
        
        System.out.println("Issuing t.interrupt()");
        
        t.interrupt();
    }
}
